package com.java.compare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableUse implements Comparable<ComparableUse> {
    private String name;
    private Integer age;
    
    public ComparableUse(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public int compareTo(ComparableUse o) {
        if (this.age == o.age) {
            // this表示被添加的元素，返回负数时被添加元素放左侧，但返回负数也意味着被添加元素更小，所以是升序排序
            return this.name.compareTo(o.name); // 升序
        }
        
        // this表示被添加的元素，返回负数时被添加元素放左侧，但返回负数也意味着被添加元素更大，所以是降序排序
        return o.age - this.age; // 降序
        
        // 升序：this - 参数
        // 降序：参数 - this
    }
    
    @Override
    public String toString() {
        return this.age + this.name;
    }
    
    public static void main(String[] args) {
        List<ComparableUse> list = new ArrayList();
        list.add(new ComparableUse("MJQ", 21));
        list.add(new ComparableUse("DCX", 22));
        list.add(new ComparableUse("SYX", 19));
        list.add(new ComparableUse("LYW", 18));
        list.add(new ComparableUse("ZZY", 20));
        list.add(new ComparableUse("YHX", 19));
        list.add(new ComparableUse("HJL", 19));
        
        System.out.println(list); // [21MJQ, 22DCX, 19SYX, 18LYW, 20ZZY, 19YHX, 19HJL]
        Collections.sort(list);
        System.out.println(list); // [22DCX, 21MJQ, 20ZZY, 19HJL, 19SYX, 19YHX, 18LYW]
    }
}

